#pragma once

#include "Log.hpp"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <string.h>

class InetAddr
{
    using Self = InetAddr;
public:

    InetAddr() = default;

    InetAddr(const struct sockaddr_in& addr)
    {
        setInetAddr(addr);
    }

    InetAddr(const std::string& ip, uint16_t port)
        :_port(port)
        ,_ip(ip)
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port); 
        inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);                    
    }

    InetAddr(uint16_t port)
        :_port(port)
        ,_ip("0")
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        _addr.sin_addr.s_addr = INADDR_ANY;
    }

    bool operator==(const Self& other) const
    {
        return other._ip == _ip && other._port == _port;
    }

    void setInetAddr(const struct sockaddr_in& addr)
    {
        _addr = addr;
        _port = ntohs(addr.sin_port);
        _ip = inet_ntoa(addr.sin_addr);
    }

    std::string getStringAddr() const
    {
        return _ip + ":" + std::to_string(_port);
    }

    socklen_t getAddrLen() const
    {
        return sizeof(_addr);
    }

    const struct sockaddr * getAddrPtr() const
    {
        return (const struct sockaddr*)&_addr;
    }

    const struct sockaddr_in& getAddr() const
    {
        return _addr;
    }

    const std::string& getIp() const
    {
        return _ip;
    }

    uint16_t getPort() const
    {
        return _port;
    }

    ~InetAddr()
    {
        ;
    }

private:

    struct sockaddr_in _addr;
    std::string _ip;
    uint16_t _port;

};
